<script lang="ts">
import {reactive, ref} from "vue";
import {Vue} from 'vue-facing-decorator';
import {str2map} from '../js/core.js';
import {ElMessage} from "element-plus";
import axios, {AxiosRequestConfig} from "axios";

export default class BaseVue extends Vue {
  // this.$refs["dataFormRef"].$el
  dataForm: any = reactive({});
  rules: any = ref({});
  visible: any = ref(false);
  //路由基础路径
  baseUrl = import.meta.env.VITE_APP_API;
  token:any=ref("")
  init(id: any) {
    this.visible = true;
  }
//提交时ref名称必须叫dataFormRef，url为提交保存的路径，type：是post还是get请求？
  dataFormSubmit(url,type) {
    const form: any = this.$refs["dataFormRef"];
    const dom = new DOMParser().parseFromString(form.$el.innerHTML, "text/html")
    //遍历所有的input
    const inputs = dom.getElementsByTagName("input");
    //输入格式为 valid="require=idCard,type=idCard,msg=请输入"
    for (let input of inputs) {
      let valid = input.getAttribute("valid");
      if (valid) {
        debugger
        let map = str2map(valid);
        //dataForm中input输入框的变量名
        let fieldName = map.get("required")
        if (fieldName) {
          //如果值为空 那么就不再给后端传值
          if (input.value === "") {
            delete this.dataForm.fieldName
          }
          let msg = map.get("msg");
          if (msg == undefined) {
            msg = input.placeholder;
          }
          this.rules[fieldName] = [{required: true, message: msg, trigger: "blur"}]
        } else {
          let fieldName = map.get("type");
          if (fieldName) {
            if (fieldName === "idCard") {

            }
          }
          //说明不包含required 属性，
          // if (arr[1].substring(5,arr[1].length)==="idCard"){
          //
          // }else if (arr[1].substring(5,arr[1].length)==="phone"){
          //
          // }else if (arr[1].substring(5,arr[1].length)==="sort"){
          //
          // }else if (arr[1].substring(5,arr[1].length)==="email"){
          //
          // }

        }
      }
    }

    // let arr = Object.entries(this.dataForm)
    // for (let entry of Object.entries(arr)) {
    //   if (entry[1] == "") {
    //     delete this.dataForm.entry[0]
    //   }
    // }
    form.validate((valid: any) => {
      // 验证通过
      if (valid) {
        if (type=="get"){
          this.get(url, this.dataForm,(data)=>{if (data.code==0){
            ElMessage.success("成功！！")
            this.visible=false;
          }})
        }else {
          this.post(url, this.dataForm,(data)=>{if (data.code==0){
            ElMessage.success("成功！！")
            this.visible=false;
          }})
        }

      } else {
        return false;
      }
    });


  }




  /**
   * http请求 ,key value格式
   * @param url
   * @param params
   * @param callback 传入一个返回值为void的函数
   */
  public get(url: string, params: { [key: string]: unknown }, callback: (data: { [key: string]: unknown }) => void): void {
    if (url.indexOf("http") != -1) {
      //传进来的是完整url地址, 不处理
    } else {
      url = this.baseUrl + url;
    }
    axios.get(url, {
      params: params,
      headers: {token:this.token }
    })
        .then(function (response) {
          console.log(response);
          callback(response.data);
        })
        .catch(function (error) {
          console.log(error);
        });
  }

  /**
   * post请求,json格式
   *
   * @param url
   * @param params
   * @param callback
   */
  public post(url: string, params: any, callback: (data: { [key: string]: unknown }) => void): void {
    url = this.baseUrl + url;
    axios.post(url,
        {
          data: params,
          headers: {token:this.token}
        })
        .then(function (response) {
          console.log(response);
          callback(response.data);
        })
        .catch(function (error) {
          console.log(error);
          ElMessage.warning("服务器异常");
        });
  }


  mounted() {

  }
}
</script>
